﻿using FAMailUtils;
using FAMailUtils.Data.DAO;
using FAMailUtils.Data.DTO;
using FAMailUtils.MailGun;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlineBusinesses.Areas.CustomerAdmin
{
    public partial class ConfigDNS : System.Web.UI.Page
    {
        ClientDAO dao = new ClientDAO();
        DomainUtils utils = new DomainUtils(ConfigurationManager.AppSettings["api-key"]);
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    ClientDTO company = dao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);

                    txtCompanyDomain.Text = company.CompanyDomain;

                    //CompanyLogo.Src = company.CompanyLogo;
                    //txtCompanyEmail.Text = company.CompanyEmail;
                    //txtCompanyAddress.Text = company.CompanyAddress;
                    //txtCompanyFax.Text = company.CompanyFax;
                    //txtCompanyName.Text = company.CompanyName;
                    //txtCompanyPhone.Text = company.CompanyPhone;


                    txtCompanyDomain.Text = company.CompanyDomain;
                    DomainItem item = utils.GetDomain(company.CompanyDomain);
                    //if (!string.IsNullOrWhiteSpace(company.CompanyDomain + ""))
                    //    txtCompanyDomain.ReadOnly = true;
                    rpt_sending.DataSource = item.sending_dns_records;
                    rpt_sending.DataBind();
                    rpt_recieving.DataSource = item.receiving_dns_records;
                    rpt_recieving.DataBind();

                    string id = dao.GetRouteIdByDomain(company.CompanyDomain);
                    if (id != "")
                    {
                        CreateResult Ritem = Routes.GetRouteByID(ConfigurationManager.AppSettings["api-key"], id);
                        if (Ritem.route.id + "" != "" && item.receiving_dns_records != null && item.receiving_dns_records.Count > 0 && item.receiving_dns_records[0].valid == "valid")
                        {
                            btnUpdateDomain.Enabled = false; txtCompanyDomain.ReadOnly = true;
                            lblStatus.ForeColor = txtCompanyDomain.BorderColor = Color.Green;
                            lblStatus.Text = "Domain đã được đăng ký";
                        }
                        else
                        {
                            txtCompanyDomain.ReadOnly = false;
                            lblStatus.ForeColor = txtCompanyDomain.BorderColor = Color.Red; lblStatus.Text = "Domain chưa được đăng ký";
                        }
                    }
                    else
                    {
                        txtCompanyDomain.ReadOnly = false;
                        lblStatus.ForeColor = txtCompanyDomain.BorderColor = Color.Red; lblStatus.Text = "Domain chưa được đăng ký";
                    }
                }
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }
        /*
        protected void btnUpdate_Click(object sender, CommandEventArgs e)
        {
            try
            {
                ClientDTO company = dao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                company.CompanyEmail = txtCompanyEmail.Text;
                company.CompanyAddress = txtCompanyAddress.Text;
                company.CompanyFax = txtCompanyFax.Text;
                company.CompanyName = txtCompanyName.Text;
                company.CompanyPhone = txtCompanyPhone.Text;
                company.CompanyLogo = CompanyLogo.Src;
                dao.Update(company);
                Response.Redirect(Request.RawUrl);
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }
        */
        protected void btnUpdateDomain_Click(object sender, CommandEventArgs e)
        {
            try
            {
                /*
                var routes = Routes.GetRoutes(ConfigurationManager.AppSettings["api-key"]);
                foreach (RoutItem route in routes.items)
                {
                    dao.SaveRoute(route);
                }*/
                ClientDTO company = dao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                company.CompanyDomain = txtCompanyDomain.Text;
                if (dao.CheckExistsDomain(txtCompanyDomain.Text, ((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID))
                {
                    dao.UpdateDomain(company);

                    string domain = txtCompanyDomain.Text;
                    DomainList list = utils.GetDomains();
                    var result = list.items.Where(a => a.name == domain);
                    bool status = false;
                    if (result.Count() == 0)
                    {
                        status = utils.AddDomain(domain, @"");
                    }
                    string id = dao.GetRouteIdByDomain(company.CompanyDomain);
                    if (id != "")
                    {
                        CreateResult Ritem = Routes.GetRouteByID(ConfigurationManager.AppSettings["api-key"], id);
                        if (Ritem.route.id + "" != "")
                            return;
                        CreateResult Rresult = FAMailUtils.MailGun.Routes.CreateRoute(ConfigurationManager.AppSettings["api-key"], ConfigurationManager.AppSettings["forwardUrl"], domain);
                        if (Rresult.message == "Route has been created" || dao.GetRouteIdByDomain(domain) == "")
                        {
                            dao.UpdateRoute(Rresult, ((AdminCustomer_Master)Page.Master).getUserLogin().Client.UserID);
                        }
                    }
                    else
                    {
                        CreateResult Rresult = FAMailUtils.MailGun.Routes.CreateRoute(ConfigurationManager.AppSettings["api-key"], ConfigurationManager.AppSettings["forwardUrl"], domain);
                        if (Rresult.message == "Route has been created" || dao.GetRouteIdByDomain(domain) == "")
                        {
                            dao.AddRoute(Rresult, ((AdminCustomer_Master)Page.Master).getUserLogin().Client.UserID);
                        }
                    }

                    Response.Redirect(Request.RawUrl);
                }
                else
                {
                    lblStatus.Text = "Domain này đã tồn tại trong hệ thống";
                    lblStatus.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }

    }
}